﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Streambolics;
using System.IO;

namespace MacNs
{
    public class HostsFileWriter : PolledComputingModule
    {
        private string _HostsFile;
        private NameDatabase _Database;
        private bool _Dirty = false;

        public HostsFileWriter (NameDatabase aDatabase)
        {
            _Database = aDatabase;
            _Database.Changed += new NameDatabaseEventHandler (_Database_Changed);
        }

        void _Database_Changed (object sender, NameDatabaseEventArgs e)
        {
            _Dirty = true;
        }

        public string HostsFile
        {
            get
            {
                return _HostsFile;
            }
            set
            {
                _HostsFile = value;
                _Dirty = true;
            }
        }

        protected override void DoPoll ()
        {
            if (_Dirty && _Database!=null && !String.IsNullOrEmpty(_HostsFile))
            {
                _Dirty = false;
                File.WriteAllText (_HostsFile, _Database.AsHostsFile ());
                GlobalLog.Log ("Hosts file {0} written", _HostsFile);
            }
        }

        protected override void DoStart ()
        {
            DeclareStarted ();
        }

        protected override void DoStop ()
        {
            DeclareStopped ();
        }
    }
}
